/**查找分页控件 -> 请求下一页 -> 增删元素 -> 加载在页面 */
async function loadNextPage() {
  let [lastNrPage] = [...document.querySelectorAll('.readpage')].slice(-1)
  let url = lastNrPage.querySelector('a:nth-of-type(4)').href

  const response = await fetch(url)
  const decoder = new TextDecoder('utf8')
  const html = decoder.decode(await response.arrayBuffer())
  let div = document.createElement('div')
  div.innerHTML = html

  let alink = document.createElement('a')
  alink.href = url
  alink.innerText = '本页'
  div.querySelectorAll('.readpage').forEach(pageDom => {
    pageDom.insertBefore(alink.cloneNode(true), pageDom.children[2])
    pageDom.removeChild(pageDom.children[3])
  })

  let containerDom = div.querySelector('.container')
  containerDom.style.width = '100%'

  let readDom = div.querySelector('.read')
  // readDom.style.borderLeftWidth = '0px'
  // readDom.style.borderRrightWidth = '0px'
  // readDom.style.borderBottomWidth = '0px'
  readDom.style.border = 'none'
  readDom.style.paddingLeft = '0px'
  readDom.style.paddingRight = '0px'
  readDom.style.background = 'rgba(219, 233, 240, 1)'

  cleanPage(div, false)


  let [lastContent] = [...document.querySelectorAll('.content')].slice(-1)
  lastContent.parentNode.appendChild(div)
  return {div, url}
}

/**从页面获取书名 */
function getBookName() {
  let el = document.querySelector('.breadcrumb li:nth-child(3)')
  return el ? el.innerText : ''
}

/**_addObserver传入targetSelector、chapterTitleSelector*/
function addObserver(dom = document, url = location.href) {
  _addObserver('.content', '.read>h1:nth-child(1)', dom, url)
}

/**包装cleanPage方法 */
function cleanPage(context = document, isFilter = true) {
  let cleanSelector = ['header', '.nav', '.readvote', '.read .readpage:nth-child(2)', '.content .report', 'footer']
  if (isFilter) {
    cleanSelector = cleanSelector.filter(i => !['header', '.nav'].includes(i))
  }
  $chromePlugin.cleanPage(context, cleanSelector)
}


$chromePlugin.loadQueueFn.push(cleanPage)